package top.continew.admin.generator.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.continew.admin.generator.mapper.TaskAssignmentMapper;
import top.continew.admin.generator.model.entity.TaskAssignmentDO;
import top.continew.admin.generator.service.TaskAssignmentService;
import top.continew.admin.system.model.resp.TaskAssignmentHandlerResp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务分配业务实现
 *
 * @author jiangjun
 * @since 2025/01/20 10:00
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskAssignmentServiceImpl extends ServiceImpl<TaskAssignmentMapper, TaskAssignmentDO> implements TaskAssignmentService {

    private final Map<String, List<java.util.Map<String, Object>>> provinceHandlersCache = new HashMap<>();
    private boolean cacheInitialized = false;

    @Override
    public void createAssignments(Long taskId, String provinceName) {
        createAssignments(taskId, provinceName, null);
    }
    
    @Override
    public void createAssignments(Long taskId, String provinceName, String batchId) {
        log.info("开始为任务ID: {}, 省区: {}, 批次ID: {} 创建分配记录", taskId, provinceName, batchId);
        
        if (StrUtil.isBlank(provinceName) || taskId == null) {
            log.warn("参数不合法: taskId={}, provinceName={}", taskId, provinceName);
            return;
        }
        
        // 获取该省区的所有负责人
        List<java.util.Map<String, Object>> handlerList = getHandlersByProvince(provinceName);
        log.info("省区 {} 的负责人数量: {}", provinceName, handlerList.size());
        
        if (handlerList.isEmpty()) {
            log.warn("省区 {} 没有找到负责人", provinceName);
            return;
        }
        
        List<TaskAssignmentDO> assignments = new ArrayList<>();
        for (java.util.Map<String, Object> handler : handlerList) {
            TaskAssignmentDO assignment = new TaskAssignmentDO();
            assignment.setTaskId(taskId);
            assignment.setHandlerId(Long.valueOf(handler.get("user_id").toString()));
            assignment.setHandlerName(handler.get("user_name").toString());
            assignment.setStatus("un_do");
            assignment.setBatchId(batchId);
            assignments.add(assignment);
            log.info("创建分配: taskId={}, handlerId={}, handlerName={}, batchId={}", 
                    taskId, assignment.getHandlerId(), assignment.getHandlerName(), batchId);
        }
        
        batchInsertAssignments(assignments);
        log.info("成功保存 {} 条分配记录", assignments.size());
    }

    @Override
    public List<TaskAssignmentHandlerResp> selectHandlers(List<Long> taskIds) {
        return getBaseMapper().selectHandlers(taskIds);
    }

    /**
     * 根据省区获取负责人列表（使用全量缓存）
     */
    private List<java.util.Map<String, Object>> getHandlersByProvince(String provinceName) {
        // 初始化缓存
        if (!cacheInitialized) {
            initProvinceHandlersCache();
        }
        return provinceHandlersCache.getOrDefault(provinceName, new ArrayList<>());
    }

    /**
     * 初始化省区负责人缓存
     */
    private void initProvinceHandlersCache() {
        try {
            List<java.util.Map<String, Object>> allHandlers = baseMapper.selectAllHandlers();
            
            for (java.util.Map<String, Object> handler : allHandlers) {
                String provinceName = handler.get("province_name").toString();
                provinceHandlersCache.computeIfAbsent(provinceName, k -> new ArrayList<>()).add(handler);
            }
            
            cacheInitialized = true;
            log.info("省区负责人缓存初始化完成，共 {} 个省区", provinceHandlersCache.size());
        } catch (Exception e) {
            log.error("初始化省区负责人缓存失败", e);
        }
    }

    @Override
    public List<TaskAssignmentDO> createAssignmentList(Long taskId, String provinceName, String batchId) {
        return createAssignmentList(taskId, provinceName, batchId, null);
    }

    /**
     * 创建任务分配列表（根据指定负责人匹配）
     */
    public List<TaskAssignmentDO> createAssignmentList(Long taskId, String provinceName, String batchId, String assignedHandler) {
        if (StrUtil.isBlank(provinceName) || taskId == null) {
            return new ArrayList<>();
        }
        
        List<java.util.Map<String, Object>> handlerList = getHandlersByProvince(provinceName);
        if (handlerList.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<TaskAssignmentDO> assignments = new ArrayList<>();
        
        // 如果指定了负责人，则只匹配该负责人
        if (StrUtil.isNotBlank(assignedHandler)) {
            for (java.util.Map<String, Object> handler : handlerList) {
                String handlerName = handler.get("user_name").toString();
                if (assignedHandler.equals(handlerName)) {
                    TaskAssignmentDO assignment = new TaskAssignmentDO();
                    assignment.setTaskId(taskId);
                    assignment.setHandlerId(Long.valueOf(handler.get("user_id").toString()));
                    assignment.setHandlerName(handlerName);
                    assignment.setStatus("un_do");
                    assignment.setBatchId(batchId);
                    assignments.add(assignment);
                    break;
                }
            }
        } else {
            // 如果没有指定负责人，则分配给所有负责人
            for (java.util.Map<String, Object> handler : handlerList) {
                TaskAssignmentDO assignment = new TaskAssignmentDO();
                assignment.setTaskId(taskId);
                assignment.setHandlerId(Long.valueOf(handler.get("user_id").toString()));
                assignment.setHandlerName(handler.get("user_name").toString());
                assignment.setStatus("un_do");
                assignment.setBatchId(batchId);
                assignments.add(assignment);
            }
        }
        
        return assignments;
    }

    @Override
    public void batchSaveAssignments(List<TaskAssignmentDO> assignments) {
        batchInsertAssignments(assignments);
    }

    @Override
    public boolean cleanProvinceHandlersCache() {
        this.cacheInitialized=false;
        this.provinceHandlersCache.clear();
        return true;
    }

    /**
     * 批量插入任务分配（按500条拆分）
     */
    private void batchInsertAssignments(List<TaskAssignmentDO> assignments) {
        int batchSize = 500;
        for (int i = 0; i < assignments.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, assignments.size());
            List<TaskAssignmentDO> batch = assignments.subList(i, endIndex);
            baseMapper.batchInsert(batch);
        }
    }
}